package com.alxy.day1.controller;

import com.alxy.day1.entity.User;
import com.alxy.day1.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;

/**
 * @author 爱莉希雅
 * @version java 17
 */
@SuppressWarnings({"all"})
@RestController
@Slf4j
@CrossOrigin
@RequestMapping("/users")
public class UserController {
    @Autowired
    UserService userService;

    // 动态查询用户列表
    @GetMapping
    public Page<User> findUsers(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "4") int size
    ) {
        // 这里为了简化，暂时不处理动态查询条件，你可以根据实际情况修改
        Specification<User> spec = null;
        Sort sort = Sort.by(Sort.Direction.ASC, "id");
        Pageable pageable = PageRequest.of(page, size, sort);
        return userService.findAll(spec, pageable);
    }

    // 添加用户
    @PostMapping
    public User addUser(@RequestBody User user) {
        return userService.save(user);
    }

    // 删除用户
    @DeleteMapping("/{id}")
    public void deleteUser(@PathVariable Long id) {
        userService.deleteById(id);
    }

    // 更新用户
    @PutMapping("/{id}")
    public User updateUser(@PathVariable Long id, @RequestBody User user) {
        user.setId(Math.toIntExact(id));
        return userService.saveAndFlush(user);
    }

    // 根据 ID 获取用户详情
    @GetMapping("/{id}")
    public User getUserById(@PathVariable Long id) {
        Optional<User> userOptional = userService.findById(id);
        return userOptional.orElse(null);
    }

}
